package 字符串.easy;

/**
 * @author Lw中
 * @date 2020/9/11 9:55
 */
public class ErBa {

    /**
     * 实现 strStr()
     * 字符串匹配算法（BF代码实现）
     * @param haystack
     * @param needle
     * @return
     */
    public static int strStr(String haystack, String needle) {
        int m = haystack.length();
        int n = needle.length();
        char[] chars1 = haystack.toCharArray();
        char[] chars2 = needle.toCharArray();
        // 比较n-m+1次
        for (int i = 0; i <= m - n; i++) {
            int k = 0;
            for (int j = 0; j < n; j++) {
                // 一一比较两个字符串中字符是否相等
                if (chars1[i + j] == chars2[j]) {
                    k++;
                } else {
                    break;
                }
            }
            if (k == n) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int i = strStr("hello", "ll");
        System.out.println(i);
    }

}
